// pages/buy/buy.js
var app = getApp();
Page({
  data: {
    hidden: true,
    offer: 0,
    items: [
      { name: '2', value: '在线支付', checked: 'true' },
    ],
    hasCarts: false,
    noCarts: true,
  },
  radioChange: function (e) {//储存支付方式
    wx.setStorageSync('payWay', e.detail.value)
  },
  onLoad: function (options) {
    var that=this
    //console.log( wx.getStorageSync('cartLists'))
    this.setData({
      groupOrder: true,
      superName: wx.getStorageSync('groupSuperName')
    })

    wx.getSystemInfo({//获取滑块的高宽
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    // console.log(that.data.superName)
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    var that = this;

    //console.log(wx.getStorageSync('groupCartLists'))
    var cartLists = wx.getStorageSync('groupCartLists');//从本地缓存获取购物车的商品信息
    // console.log(isNaN(cartLists[0].totalPrices))
    for (var y in cartLists) {//遍历购物车
      cartLists[y].totalPrices = parseFloat(cartLists[y].unitPrice * cartLists[y].quantity).toFixed(2)//让购物车里的单价乘以数量，得到单件商品的总价
    }
    this.setData({ cartLists: cartLists });//同步显示到页面
    wx.setStorageSync('groupCartLists', cartLists)//同步储存在本地以备购买时调用
    var totalMoneyArr = [];
    for (var index in this.data.cartLists) {//计算总的价格
      totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));

    }
    var totalMoney = totalMoneyArr.reduce(function (a, b) {
      return (parseFloat(a) + parseFloat(b)).toFixed(2);
    });
    that.setData({//将总价格显示在页面
      totalMoney: totalMoney
    });
    wx.setStorage({ key: "totalMoney", data: that.data.totalMoney })//储存在本地以备购买时调用
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  confirm: function () {//点击确认进入填写地址页面
    var that = this;
    that.setData({
      hidden: true
    })
    wx.navigateTo({
      url: '/pages/addAddress/addAddress',
    })
  },
  cancel: function () {//点击取消则不进入写地址页面
    var that = this;
    that.setData({
      hidden: true
    })
  },

  addQuantity: function (e) {//增加单个商品数量
    this.changeCartItemQuantity('+', e)
  },

  minusQuantity: function (e) {//减少单个商品数量
    this.changeCartItemQuantity('-', e)
  },

  changeCartItemQuantity: function (op, e) {//改变单个商品数量
    var that = this;
    var cartLists = this.data.cartLists//找到储存在本地购物车的商品信息
    var cart = cartLists.filter(function (ele) {//过滤出点击加减的商品在本地储存的唯一商品ID
      return ele.productId === e.currentTarget.dataset.id

    })[0]
    if (op === '-' && cart.quantity > 1) {//如果符号为－，则商品数量减一
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '+') {//如果符号为+，则商品数量加一
      if (cart.quantity == cart.repertory) {//如果增加的数量大于库存，则取消增加；
        wx.showToast({
          title: "库存不足",
          icon: "loading"
        })
      } else {
        cart.quantity += 1;
      }
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '-' && cart.quantity == 1) {
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2);
      //  console.log(cart);
    }
    for (var quantity in cartLists) {//移除购物车中数量为0的对象
      if (cartLists[quantity].quantity == 0) {
        cartLists.splice(quantity, 1)
      }
    }
    this.setData({ cartLists: cartLists })//同时将所修改的数量保存到当前页面的购物车中
    //  console.log(cartLists)
    wx.setStorageSync('groupCartLists', cartLists);
    if (cartLists != "") {//当购物车不为空的时候，在计算总金额
      var totalMoneyArr = [];
      for (var index in this.data.cartLists) {
        totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));
      }
      var totalMoney = totalMoneyArr.reduce(function (a, b) {
        return (parseFloat(a) + parseFloat(b)).toFixed(2);
      });
      that.setData({
        totalMoney: totalMoney
      });
     // app.cartTotalMoney = totalMoney;
      // wx.setStorage({key:"cartTotalMoney",data:that.data.totalMoney})
      wx.setStorage({
        key: 'totalMoney',
        data: that.data.totalMoney
      })//同步储存到购物车
      // console.log(cartLists)
    } else {
      wx.setStorageSync('groupCartLists', "");
      that.setData({
        hasCarts: true,
        noCarts: false
      })
    }
  }

  ,
  getCartInfo: function () {//将用户购买的商品以及用户信息发送到后台生成预支付订单
    var groupDetail = wx.getStorageSync('groupCartLists')
   // console.log(groupDetail[0].quantity)
    // console.log(groupDetail)
    wx.request({
      url: app.globalData.allUrl + "/YMGW/weChatPayAction/WeChatPay",
      data: {
        userID: wx.getStorageSync('userid'),
        seckillID: groupDetail[0].productId,
        num: groupDetail[0].quantity,
        typeId: 2
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        console.log(res.data)
        // success
        if (res.data.packages) {
          var pay = res.data;
          wx.requestPayment({//如果从后台获取支付信息成功。则调用微信支付接口
            timeStamp: pay.timeStamp,
            nonceStr: pay.nonceStr,
            package: pay.packages,
            signType: pay.signType,
            paySign: pay.paySign,
            success: function (res) {
              // success
            //  console.log(res)
              wx.showToast({
                title: '微信支付成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(function () {//两秒后跳转到我的页面
                wx.switchTab({
                  url: '../my/my',
                  success: function (res) {
                    // success
                  }
                })
              }, 2000)    
            }, fail(res) { console.log(res) }
          })

        }
      }
    })
  },





})